﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.ServiceLayer.EntityManagement.Constants;

namespace Company.Merchandising.ServiceLayer.EntityManagement
{
	public class ChainStoreManager : BaseManager
	{
		public ChainStoreManager(MerchModelEntities modelEntities) : base(modelEntities) { }

		public void UpdateChainStore(DTOChainStore dtoChainStore)
		{
			DACChainStore dacChainStore = new DACChainStore(_modelEntities);
			if (dacChainStore.GetChainStoresByNameAndOtherId(dtoChainStore.Name, dtoChainStore.Id).Count() > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ProvinceAlreadyExist, dtoChainStore.Name));
			}

			var foundChainStore = dacChainStore.GetChainStoreById(dtoChainStore.Id);
			if (foundChainStore == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ChainStoreDoesNotExistAnyMore, dtoChainStore.Id));
			}

			foundChainStore.Name = dtoChainStore.Name;
			_modelEntities.SaveChanges();
		}

		public void AddChainStore(DTOChainStore dtoChainStore)
		{
			DACChainStore dacChainStore = new DACChainStore(_modelEntities);
			if (dacChainStore.GetChainStoresByName(dtoChainStore.Name).Count() > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ChainStoreAlreadyExist, dtoChainStore.Name));
			}

			var newChainStore = new ChainStore();
			newChainStore.Name = dtoChainStore.Name;
			_modelEntities.AddObject(newChainStore.GetType().Name, newChainStore);
			_modelEntities.SaveChanges();
		}

		public void DeleteChainStore(int chainStoreId)
		{
			DACChainStore dacChainStore = new DACChainStore(_modelEntities);
			var foundChainStore = dacChainStore.GetChainStoreById(chainStoreId);
			if (foundChainStore == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ChainStoreDoesNotExistAnyMore, chainStoreId));
			}

			if (!foundChainStore.Locations.IsLoaded)
			{
				foundChainStore.Locations.Load();
			}

			if (foundChainStore.Locations.Count > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.ChainStorePossessesLocations, chainStoreId));
			}

			_modelEntities.DeleteObject(foundChainStore);
			_modelEntities.SaveChanges();
		}
	}
}
